package com.haoqizhe.kernel.config;

import cn.hutool.core.util.StrUtil;
import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

/**
*
* hibernate validate 数据校验配置
* 获取messagePath 默认提醒信息
*
* @author haoqizhe.li
* @date 2018/4/9 15:17
**/
@Configuration
public class HibernateValidateConfig {

	@Value("${hibernate.validate.message.path:#{null}")
	private String messagePath;

	@Bean
	public ReloadableResourceBundleMessageSource messageSource() {
		ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();

		if(StrUtil.isNotBlank(messagePath)){
			messagePath += ",classpath:message/ValidationMessages";
		}else{
			messagePath = "classpath:message/ValidationMessages";
		}

		reloadableResourceBundleMessageSource.setBasenames(messagePath.split(","));
		reloadableResourceBundleMessageSource.setUseCodeAsDefaultMessage(true);
		reloadableResourceBundleMessageSource.setDefaultEncoding("UTF-8");
		reloadableResourceBundleMessageSource.setCacheSeconds(60);
		return reloadableResourceBundleMessageSource;
	}

	@Bean
	public LocalValidatorFactoryBean validator() {
		LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
		localValidatorFactoryBean.setProviderClass(HibernateValidator.class);
		localValidatorFactoryBean.setValidationMessageSource(messageSource());
		return localValidatorFactoryBean;
	}
}
